#!/bin/bash
# 安装Tomcat及配置服务

# 引入公共配置
source ./common.sh

# 确保应用目录存在
app_home

function install_tomcat() {
    local version=`echo ${Version} |awk -F. '{print $1}' `
    local appname="apache-tomcat-${Version}.tar.gz"
    
    if [ ! -e "${APPS_HOME}/${appname}" ];then
        echo "正在下载Tomcat ${Version}..."
        wget -P ${APPS_HOME} ${TOMCAT_NAME}${version}/v${Version}/bin/${appname} --no-check-certificate
        if [ $? -ne 0 ]; then
            error_exit "Tomcat下载失败"
        fi
    fi
    
    tar xf ${APPS_HOME}/apache-tomcat-${Version}.tar.gz -C ${Basedir}/ 
    mv ${Basedir}/apache-tomcat-${Version} ${Basedir}/tomcat
}

function configure_tomcat_service() {
    if [[ ! -f "${TOMCAT_SERVICE}" ]];then
        echo "创建tomcat服务文件"
        cat > ${TOMCAT_SERVICE} <<EOF
[Unit]
Description=Tomcat
After=network-online.target
[Service]
Type=simple
User=tomcat
Group=tomcat
ExecStart=${Basedir}/tomcat/bin/startup.sh
ExecStop=${Basedir}/tomcat/bin/shutdown.sh

Restart=always
RestartSec=1
StartLimitInterval=0
ProtectHome=yes
NoNewPrivileges=yes
[Install]
WantedBy=multi-user.target
EOF

        # 创建tomcat用户
        if ! id -u tomcat >/dev/null 2>&1; then
            useradd -r -s /sbin/nologin tomcat
        fi
        chown -R tomcat:tomcat ${Basedir}/tomcat
        
        systemctl daemon-reload
        systemctl enable tomcat
        systemctl start tomcat
        success_msg "Tomcat服务配置完成"
    else
        echo "tomcat服务文件已存在"
    fi
}

echo "开始安装Tomcat..."

# 检查JDK是否已安装
java -version
if [ $? -ne 0 ];then
    error_exit "未检测到JDK，请先安装JDK"
fi

Tomcat_All_Version=`curl -s https://dlcdn.apache.org/tomcat/|grep tomcat-|awk -F'>' '{print $3}'|awk -F '/' '{print $1}'|sed '$d'`
echo "可用的Tomcat大版本: $Tomcat_All_Version"

read -p "请输入要安装的Tomcat大版本(如tomcat-9): " qwe
limi_version=$(echo $qwe|awk -F'-' '{print $NF}')
echo "该版本下的可用具体版本: "
curl -s https://dlcdn.apache.org/tomcat/$qwe/|awk -F'>' '{print $3}'|grep v$limi_version|tr -d '/</a'|tr -d 'v' 

read -p "请输入要安装的Tomcat具体版本: " Version
if [ -z "${Version}" ];then
    error_exit "版本号不能为空"
fi

install_tomcat
configure_tomcat_service

success_msg "Tomcat ${Version} 安装完成"
